<template>
  <div class="">
    <!-- ↓↓↓ 社区人员 ↓↓↓ -->
    <div>
      <div id="cardArea">
        <el-card id="totalCount" class="box-card">
          <div class="info-label"><b>总订单数</b></div>
          <div class="info-label2">
            <svg-icon icon-class="table" class="icon" class-name="card-panel-icon" style="color:#409EFF;font-size:50px;float:left" />
            <span id="totalUser-num" class="num">{{ totalOrders }}<span style="font-size:15px">笔</span></span>
          </div>
        </el-card>

        <el-card id="contactCount" class="box-card">
          <div class="info-label"><b>分期订单</b></div>
          <div class="info-label2" style="color:#67C23A  ">
            <svg-icon icon-class="table" class="icon" class-name="card-panel-icon" style="font-size:50px;float:left" />
            <span id="contactUser-num" class="num">{{ totalOrdersStage }}<span style="font-size:15px">笔</span></span>
          </div>
        </el-card>
      </div>
      <div id="cardArea">
        <el-card id="feverCount" class="box-card">
          <div class="info-label"><b>直接订单</b></div>
          <div class="info-label2" style="color:#F56C6C">
            <svg-icon icon-class="table" class="icon" class-name="card-panel-icon" style="font-size:50px;float:left" />
            <span id="feverUser-num" class="num">{{ totalOrdersNotStage }}<span style="font-size:15px">笔</span>  </span>
          </div>
        </el-card>

        <el-card id="hospitalCount" class="box-card">
          <div class="info-label"><b>总交易额</b></div>
          <div class="info-label2" style="color: #E6A23C">
            <svg-icon icon-class="form" class="icon" class-name="card-panel-icon" style="font-size:50px;float:left" />
            <span id="hostipalUser-num" class="num">￥{{ referenceRatio }}<span style="font-size:15px">元</span></span>
          </div>
        </el-card>
      </div>
    </div>
    <div class="search-chart">
      <div class="search-form">
        <el-form ref="search" :model="search" :inline="true" :rules="rules">
          <el-form-item label="统计方式" prop="unit">
            <el-select v-model="search.unit" placeholder="请选择" style="width:100px">
              <el-option label="周" value="1" />
              <el-option label="月" value="2" />
              <el-option label="季" value="3" />
              <el-option label="年" value="4" />
            </el-select>
          </el-form-item>
          <el-form-item prop="date">
            <el-date-picker v-model="search.date" type="date" placeholder="请选择日期" style="width:140px" />
          </el-form-item>
          <el-form-item label="机构" prop="orgId">
            <el-select v-model="search.orgId" placeholder="请选择一家机构" style="width:180px">
              <el-option v-for="o in org" :key="o.campusId" :value="o.campusId" :label="o.campusName" />
            </el-select>
          </el-form-item>
          <el-form-item label="年龄区间" prop="minAge">
            <el-input v-model="search.minAge" style="width:80px" maxlength="3" />
          </el-form-item>
          -
          <el-form-item prop="maxAge">
            <el-input v-model="search.maxAge" style="width:80px" maxlength="3" />
          </el-form-item>
          <el-form-item label="价格区间" prop="minPrice">
            <el-input v-model="search.minPrice" style="width:80px" maxlength="5" />
          </el-form-item>
          -
          <el-form-item prop="maxPrice">
            <el-input v-model="search.maxPrice" style="width:80px" maxlength="5" />
          </el-form-item>
          <el-form-item label="支付方式" prop="payType">
            <el-select v-model="search.payType" placeholder="" style="width:100px">
              <el-option label="银联支付" value="0" />
              <el-option label="分期支付" value="1" />
              <el-option label="微信支付" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" style="margin-left:10px" @click="chartSearch('search')">统计</el-button>
            <el-button icon="el-icon-refresh" circle @click="refresh()" />
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="tab">
      <el-tabs v-model="activeName">
        <el-tab-pane label="统计图" name="first">
          <div class="pie">
            <el-card class="community-pie-card">
              <div id="myPie1">
                <!-- 123 -->
              </div>
            </el-card>
          </div>
        </el-tab-pane>
        <el-tab-pane label="统计表" name="second">
          <el-card class="orders-card">
            <span class="orders-title" style=" color: #606266; ">订单信息</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span>总金额：{{ allMoney }}￥</span>
            <el-button class="download" type="primary" icon="el-icon-download" size="mini" @click="exportExcel" />
            <div>
              <el-table
                v-loading="listLoading"
                :data="list.slice((currentPage-1)*pagesize,currentPage*pagesize)"
                element-loading-text="Loading"
                border
                fit
                highlight-current-row
                class="orderTable"
              >
                <el-table-column
                  label="序号"
                  type="index"
                  width="80"
                  align="center"
                />

                <el-table-column
                  align="center"
                  prop="id"
                  label="订单编号"
                />

                <el-table-column
                  align="center"
                  prop="userPhone"
                  label="会员手机号"
                />

                <el-table-column
                  align="center"
                  prop="userName"
                  label="会员姓名"
                />

                <el-table-column
                  align="center"
                  prop="orgName"
                  label="品牌名称"
                />

                <el-table-column
                  align="center"
                  prop="campusName"
                  label="机构名称"
                />

                <el-table-column
                  align="center"
                  prop="lessonName"
                  label="服务项目"
                />

                <el-table-column
                  align="center"
                  prop="payTime"
                  label="支付时间"
                />

                <el-table-column
                  align="center"
                  prop="payType"
                  label="支付方式"
                >
                  <template slot-scope="Scope">
                    <span v-if="Scope.row.payType==0">银联支付</span>
                    <span v-if="Scope.row.payType==1">分期支付</span>
                    <span v-if="Scope.row.payType==2">微信支付</span>
                  </template>
                </el-table-column>

                <el-table-column
                  align="center"
                  prop="totalPrice"
                  label="总金额"
                >
                  <template slot-scope="Scope">
                    <span>￥{{ Scope.row.totalPrice/100 }}</span>
                  </template>
                </el-table-column>
              </el-table>

              <div id="pages">
                <el-pagination
                  :current-page="currentPage"
                  :page-sizes="[5,10,20,50,100,1000]"
                  :page-size="pagesize"
                  layout="total, sizes,prev, pager, next"
                  :total="list.length"
                  prev-text="上一页"
                  next-text="下一页"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
              </div>
            </div>
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import { chart, chartSearch, conditionSearch, getOrgCount, getOrgMoney, getOrgUser, selectCampusByorgId } from '@/api/statistic'
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
export default {
  name: 'RecommendStatistic',
  // import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    // 这里存放数据
    return {
      totalOrders: '',
      totalOrdersStage: '',
      totalOrdersNotStage: '',
      referenceRatio: '',
      currentPage: 1, // 默认显示页面为1
      pagesize: 5, //    每页的数据条数
      list: [],
      activeName: 'first',
      search: {
        unit: '',
        date: '',
        orgId: '',
        minAge: '',
        maxAge: '',
        minPrice: '',
        maxPrice: '',
        payType: ''
      },
      select: {},
      listLoading: false,
      dialogFormVisible: false,
      order: {},
      visible: false,
      org: [],
      campuslist: [],
      x_chart: [],
      nameList: [],
      chartlist: [],
      searchdate: '',
      allMoney: 0,
      rules: {
        date: [
          { required: true, message: '请选择日期', trigger: 'blur' }
        ],
        unit: [
          { required: true, message: '请选择统计方式', trigger: 'blur' }
        ],
        orgId: [
          { required: true, message: '请选择一家品牌', trigger: 'blur' }
        ],
        minAge: [
          { validator: this.validateCom, trigger: 'blur' },
          { validator: this.validateMin, trigger: 'blur' }
        ],
        maxAge: [
          { validator: this.validateCom, trigger: 'blur' },
          { validator: this.validateMax, trigger: 'blur' }
        ],
        minPrice: [
          { validator: this.validateComPrice, trigger: 'blur' },
          { validator: this.validateMinPrice, trigger: 'blur' }
        ],
        maxPrice: [
          { validator: this.validateComPrice, trigger: 'blur' },
          { validator: this.validateMaxPrice, trigger: 'blur' }
        ]
      },
      orgName: '',
      orgId: ''
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.orgCount()
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.getChartData()
  },
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {},
  // 方法集合
  methods: {
    exportExcel() {
      var wb = XLSX.utils.table_to_book(document.querySelector('.orderTable'))
      var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
      try {
        FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '订单数据.xlsx')
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout)
      }
      return wbout
    },
    orgCount() {
      getOrgUser().then((resp) => {
        this.orgName = resp.obj.orgName
        this.orgId = resp.obj.orgId
        getOrgCount(this.orgName).then((resp) => {
          this.totalOrders = resp.obj.obj.allnumber
          this.totalOrdersStage = resp.obj.obj.fenqinumber
          this.totalOrdersNotStage = resp.obj.obj.zhijienumber
        })
        getOrgMoney(resp.obj.orgId).then((resp) => {
          this.referenceRatio = resp.obj / 100
        })
      })
    },
    handleSizeChange: function(size) {
      this.pagesize = size
    },
    // 点击第几页
    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage
    },
    handleClick(row) {
      console.log(row)
    },
    getChartData() {
      getOrgUser().then((resp) => {
        this.orgId = resp.obj.orgId
        selectCampusByorgId(this.orgId).then((resp) => {
          this.org = resp.obj
          chart(this.org[0].campusId, this.orgId, 1).then((resp) => {
            this.list = resp.obj.ordersList
            for (var i = 0; i < this.list.length; i++) {
              this.allMoney = this.allMoney + this.list[i].totalPrice / 100
            }
            this.x_chart = resp.obj.dateList
            this.nameList = resp.obj.nameList
            this.chartlist = resp.obj.countOrgOrdersList
            this.draw()
          })
        })
      })
    },
    refresh() {
      this.search.unit = ''
      this.search.date = ''
      this.search.orgId = ''
      this.search.minAge = ''
      this.search.maxAge = ''
      this.search.minPrice = ''
      this.search.maxPrice = ''
      this.search.payType = ''
      this.allMoney = 0
      this.getChartData()
    },
    chartSearch(search) {
      this.allMoney = 0
      this.$refs[search].validate((valid) => {
        if (valid) {
          chartSearch(this.search.orgId, this.orgId, this.search.date, this.search.unit, this.search.minAge, this.search.maxAge, this.search.minPrice, this.search.maxPrice, this.search.payType).then((resp) => {
            this.list = resp.obj.ordersList
            for (var i = 0; i < this.list.length; i++) {
              this.allMoney = this.allMoney + this.list[i].totalPrice / 100
            }
            this.x_chart = resp.obj.dateList
            this.nameList = resp.obj.nameList
            this.chartlist = resp.obj.countOrgOrdersList
            this.draw()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    draw() {
      const pieChart1 = this.$echarts.init(document.getElementById('myPie1'))
      pieChart1.setOption({
        title: {
          text: '交易量统计'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            animation: false,
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend: {
          data: this.nameList
        },
        toolbox: {
          feature: {
            dataZoom: {
              yAxisIndex: 'none'
            },
            saveAsImage: {}
          }
        },
        axisPointer: {
          link: { xAxisIndex: 'all' }
        },
        dataZoom: [
          {
            show: true,
            realtime: true,
            start: 0,
            end: 50,
            xAxisIndex: 0
          }
        ],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },

        // xAxis: [
        //   {
        //     type: 'category',
        //     boundaryGap: false,
        //     data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
        //   }
        // ],
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            axisLine: { onZero: true },
            data: this.x_chart
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: this.chartlist
      })
    },
    conditionQuery() {
      console.log(this.search)
      conditionSearch(this.search).then((data) => {
        this.list = data.obj
        this.search = {}
        this.currentPage = 1
      })
    },
    validateCom(rule, value, callback) {
      const one = Number(value)
      if (Number.isInteger(one)) {
        if (one < 0) {
          return callback(new Error('年龄必须大于0'))
        } else if (one > 100) {
          return callback(new Error('年龄必须小于100'))
        }
        return callback()
      }
      return callback(new Error('年龄必须为正整数'))
    },
    validateMin(rule, value, callback) {
      const one = Number(value)
      const max = Number(this.search.maxAge)
      if (!max || one < max) {
        return callback()
      }
      return callback(new Error('不得大于最大值'))
    },
    validateMax(rule, value, callback) {
      const one = Number(value)
      const min = Number(this.search.minAge)
      if (!min || one > min) {
        return callback()
      }
      return callback(new Error('不得小于最小值'))
    },
    validateComPrice(rule, value, callback) {
      const one = Number(value)
      if (Number.isInteger(one)) {
        if (one < 0) {
          return callback(new Error('价格必须大于0'))
        } else if (one > 99999) {
          return callback(new Error('价格必须小于99999'))
        }
        return callback()
      }
      return callback(new Error('价格必须为正整数'))
    },
    validateMinPrice(rule, value, callback) {
      const one = Number(value)
      const max = Number(this.search.maxPrice)
      if (!max || one < max) {
        return callback()
      }
      return callback(new Error('不得大于最大值'))
    },
    validateMaxPrice(rule, value, callback) {
      const one = Number(value)
      const min = Number(this.search.minPrice)
      if (!min || one > min) {
        return callback()
      }
      return callback(new Error('不得小于最小值'))
    }
  } // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style  scoped>

#cardArea{
    margin: 50px;
    display: flex;
    justify-content: center;

}

 .box-card {
    margin-left: 30px;
    width: 400px;
    height: 180px;
  }

 .info-label{
    line-height: 50px;
    margin-top: 0px;
  }

  .info-label2{
    line-height: 100px;
    margin-top: 0px;
  }

  #totalUser-num{
  color: #409EFF;
  /* font-size: 35px; */
}

.info-label
{
  color: #606266;
  /* text-align: right; */
  /* font-size:35px; */
}

.num{
  float:right;
  text-align: right;
  font-size: 35px;
  margin-right: 10px;
  /* margin-left: 60%; */
}

.icon{
  margin-top: 15px;
  text-align: left;
}
.tab{
  margin: 0 auto;
  width: 1400px;
}
.pie{
   margin: 50px auto;
   width: 1400px;
}
#myPie1{
  width: 1300px;
  height: 540px;
}
#table-area{
  margin-left: 10px;
  margin-right: 10px;
}
#search-card {
  margin-left: 50px;
  margin-top: 30px;
  width: 100%;
  height: 70px;
  overflow-x: hidden;
}
.orders-card{
  width: 1400px;
  margin: 50px auto;
}
.search-chart{
  width: 1500px;
  margin: 0 auto;
  /* margin-left: 50px; */
}
.search-form{
  width: 99%;
  margin: 0 auto;
}
.orders-title{
  color: #606266;
  font-size: 24px;
  margin-bottom: 20px;
}
.download{
  float: right;
  margin-bottom: 15px;
  margin-right: 40px;
}
</style>
